/**
 * @file last.d.js
 *
 * scripts for last page of /zizhuyou
 *
 * @author dh2997
 * @version c
 * @data 2013-8-13
 */

;
/**
 * @file last.d.js
 *
 * scripts for last page of /zizhuyou
 *
 * @author dh2997
 * @version c
 * @data 2013-8-13
 */

;
(function() {

	/**
	 *  img player
	 */
	TCent.behaviors.img_player = {
		attach: function() {
			fish.all('.img_player').once('img-player', function() {
				if (!fish.one('#picBox', this).length) return;

				slider();

				fish.one(this).hover(function() {
					fish.one(this).addClass('img_player_active');
				}, function() {
					fish.one(this).removeClass('img_player_active');
				})
			})
		}
	}

	// slider function for img player come from other guys,
	// and it need to redesign!
	// http://bbs.csdn.net/topics/390646816
	function slider() {

		function G(s) {
			return document.getElementById(s);
		}

		function getStyle(obj, attr) {
			if (obj.currentStyle) {
				return obj.currentStyle[attr];
			} else {
				return getComputedStyle(obj, false)[attr];
			}
		}

		function Animate(obj, json) {
			if (obj.timer) {
				clearInterval(obj.timer);
			}
			obj.timer = setInterval(function() {
				for (var attr in json) {
					var iCur = parseInt(getStyle(obj, attr));
					iCur = iCur ? iCur : 0;
					var iSpeed = (json[attr] - iCur) / 3;
					iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
					obj.style[attr] = iCur + iSpeed + 'px';
					if (iCur == json[attr]) {
						clearInterval(obj.timer);
					}
				}
			}, 30);
		}

		var oPic = G("picBox");
		var oList = G("listBox");

		var oPrev = G("prev");
		var oNext = G("next");

		var oPicLi = oPic.getElementsByTagName("li");

		var oListLi = oList.getElementsByTagName("li");
		var len1 = oPicLi.length;
		var len2 = oListLi.length;

		var oPicUl = oPic.getElementsByTagName("ul")[0];
		var oListUl = oList.getElementsByTagName("ul")[0];
		var w1 = oPicLi[0].offsetHeight;
		var w2 = oListLi[0].offsetHeight;

		oPicUl.style.height = w1 * len1 + "px";
		oListUl.style.height = w2 * len2 + "px";

		var index = 0;

		var num = 3;
		var num2 = Math.ceil(num / 3);

		// 添加自动播放
		var timer;

		function autoChange() {
			if (timer) clearTimeout(timer)
			timer = setTimeout(function() {
				index++;
				index = index == len2 ? 0 : index;
				Change();
			}, 3000);
		}

		function Change() {

			Animate(oPicUl, {
				top: -index * w1
			});

			if (index < num2) {
				Animate(oListUl, {
					top: 0
				});
			} else if (index + num2 < len2) {
				Animate(oListUl, {
					top: -(index - num2) * w2
				});
			} else {
				Animate(oListUl, {
					top: -(len2 - num) * w2
				});
			}

			for (var i = 0; i < len2; i++) {
				oListLi[i].className = "";
				if (i == index) {
					oListLi[i].className = "on";
				}
			}

			var img = fish.one(fish.all('li img', oPicUl)[index]),
				orisrc = img.attr('orisrc'),
				src = img.attr('src');

			if (orisrc && orisrc != src) {
				img.attr('src', orisrc);
			}

			autoChange();
		}

		oNext.onclick = oNext.onclick = function() {
			index++;
			index = index == len2 ? 0 : index;
			Change();
		}

		oPrev.onclick = oPrev.onclick = function() {
			index--;
			index = index == -1 ? len2 - 1 : index;
			Change();
		}

		for (var i = 0; i < len2; i++) {
			oListLi[i].index = i;
			oListLi[i].onclick = function() {
				index = this.index;
				Change();
			}
		}

		autoChange();

		// 鼠标悬浮于主图，停止自动更新。
		fish.one(oPic).hover(function() {
			if (timer) clearTimeout(timer);
		}, function() {
			autoChange();
		})
	}


	/**
	 * packages
	 */
	TCent.settings.packages = TCent.settings.packages || {
		routerid: 0,
		// 相关url
		url: {
			prices: 'ajax/getPackagePrices.html?',
			// 套餐预订地址
			order: 'book.2.11.html?',
			// 套餐的价格日期列表
			date: 'ajax/getPackageDate.html?'
		}
	}

	TCent.behaviors.packages = {
		attach: function() {
			fish.all('#router').once('packages', function() {
				TCent.packages.init();

				// sceondary 中的预订按钮
				// fish.all('.action a', this).hasClass('disabled') ? fish.all('.secondary_nav .action a').addClass('disabled') : fish.all('.secondary_nav .action a').removeClass('disabled');

				fish.all('.secondary_nav .action a').on('click', function(e) {
					if (fish.one(this).hasClass('disabled')) {
						// 禁用的按钮啥都不起作用。
						fish.preventDefault(e);
						return;
					}
				});
			})
		}
	}

	TCent.packages = {
		routerid: 0,
		id: 0,
		title: '',
		date: '',
		router_prices: [], // 线路总体的价格
		prices: [], // 套餐的价格

		init: function() {
			// A. 设置routerid
			this.routerid = TCent.settings.packages.routerid;
		},
		// 提交
		submit: function() {
			if (!this.id) return;

			// A. 给弹框
			fish.mPop({
				content: fish.all('.overlay_calendar'),
				width: 678
			})

			fish.all('.overlay_calendar .close').on('click', function(e) {
				fish.preventDefault(e);
				fish.mPop.close();
			})

			// B. 绑定日期控件
			// 日历控件想要多一个关闭按钮，并且每次点击都应该重新绑定一个mcal
			var new_mcal_id = 'overlay_calendar_' + TCent.uuid++;
			fish.all('.overlay_calendar .calendar_wrapper').html('');
			fish.all('.overlay_calendar .calendar_wrapper').html((this.title ? '<h3>' + this.title + '</h3>' : '') + '<span id="' + new_mcal_id + '"></span>'),
				routerid = this.routerid,
				packageid = this.id;

			fish.all('#' + new_mcal_id).calendar({
				url: TCent.settings.packages.url.date + '&packageid=' + packageid + '&comedate={year}-{month}' + '&routerid=' + this.routerid,
				getMonthData: this.processData,
				getDayData: this.makeItem,
				startTime: this.getNow(),
				// endTime : fish.parseTime(this.getNow(),{months:2}),
				click: function(data, year, month, day) {
					date = fish.parseTime(year + '-' + month + '-' + day);
					var url = TCent.settings.packages.url.order + '&routerid=' + routerid + '&packageid=' + packageid + '&num=' + 1 + '&date=' + date;

					location.href = url;
				},
				clickable: function(data, year, month, day) {
					if (!data) {
						return false;
					} else {
						if (data.advance) return false; // 需要提前预订的，不可点击
						if (data.time) return false; // 需今日几点前预订
						if (!data.price) return false; // 无价格的，不可点击
						if (data.amount == -3) return false; // 售罄的，不可点击

						return true;
					}
				}
			})

		},

		// 得到今天的日期
		getNow: function() {
			if (this.now) return this.now;

			var date = new Date();
			date.setTime(date.getTime());

			var year = date.getFullYear(),
				month = date.getMonth() + 1,
				day = date.getDate();

			month = month >= 10 ? month : ('0' + month)

			this.now = year + '-' + month + '-' + day;
			return this.now;
		},

		// 今天的日期
		now: '',

		// 过滤日期格式
		//
		// @modify 2013-12-12 添加会员周。 http://tccommon.17usoft.com/tcproject/Task/View.aspx?id=37780
		processData: function(data, dataYear, dataMonth) {
			var prices = [];

			for (var i = 1; i <= 31; i++) {
				prices.push({
					day: i
				});
			}

			// 是否强制生成新的日历提示

			for (var i = 0; i < data.data.length; i++) {
				var day = parseInt(data.data[i].day),
					price = parseInt(data.data[i].price),
					amount = parseInt(data.data[i].amount ? data.data[i].amount : 0),
					member_weekend = parseInt(data.data[i].member_weekend ? data.data[i].member_weekend : 0), // 是否属于会员周
					advance = 0, // 提前预订天数
					time = '';

				if (data.advance && (fish.parseDate(dataYear + '-' + dataMonth + '-' + day).getTime() < fish.parseDate(data.now.split(' ')[0], {
					days: data.advance
				}).getTime())) {
					// 套餐需要提前预订，并且查询的时间小于当前时间+提前量则显示需要提前预订。
					advance = data.advance;
				}
				// 日历控件中的日期从0开始计数。
				prices[day - 1].price = price;
				prices[day - 1].amount = amount;
				prices[day - 1].advance = advance;
				prices[day - 1].member_weekend = member_weekend;

				// 提前data.time之前预定
				if (fish.parseDate(dataYear + '-' + dataMonth + '-' + day).getTime() == fish.parseDate(data.now.split(' ')[0], {
					days: data.advance
				}).getTime()) {
					// 是提前N天后的那一天。
					if (fish.parseDate(data.now, {
						days: data.advance
					}).getTime() >= fish.parseDate(dataYear + '-' + dataMonth + '-' + day + ' ' + data.time).getTime() || !data.time) {
						// 该天的下单时间在data.time之后
						prices[day - 1].time = data.time;
						time = data.time;
					}
				}

				// 找到最接近的可定日期
				if (!advance && !time && price && (amount != -3)) {
					// 可定的。
					if (!TCent.packages.closetDateOfOrderable) {
						TCent.packages.closetDateOfOrderable = dataYear + '-' + dataMonth + '-' + day;
					}
				}
			}

			// 根据日期数据做出相应的提示。
			TCent.packages.initCalTip(data);

			return prices;
		},
		// 创建、设置每个日期的格式
		// 数据类型 -1未设置库存，-2库存紧张（满房了但为关房） -3 满房（满房了并且关房了）
		makeItem: function(data, year, month, day) {
			var priceInfo;

			if (data.advance) {
				// 提前预订
				priceInfo = '';
				return priceInfo;
			}

			if (data.time) {
				// 今日提前N小时预订
				priceInfo = '';
				return priceInfo;
			}

			if (data && data.price) {
				if (data.amount >= 5) {
					priceInfo = '<span>¥<strong>' + data.price + '</strong></span>';
				} else if (data.amount > 0) {
					priceInfo = '<span>¥<strong>' + data.price + '</strong></span>';
					priceInfo += '<i>仅剩' + data.amount + '份</i>';
				} else if (data.amount == -1) {
					priceInfo = '<span>¥<strong class="notsure">' + data.price + '</strong></span>';
				} else if (data.amount == -2) {
					priceInfo = '<span>¥<strong>' + data.price + '</strong></span>';
					priceInfo += '<i class="storage_rare">库存紧张</i>';
				} else if (data.amount == -3) {
					priceInfo = '<span class="empty">售罄</span>';
				} else {
					priceInfo = '<span>¥<strong>' + data.price + '</strong></span>';
				};

				// 属于会员周且没有售罄
				if (data.member_weekend && data.amount > -3) {
					priceInfo = '<span>¥<strong>' + data.price + '</strong></span>' + '<div class="member_weekend">会员周更便宜</div>';
				}
			} else {
				priceInfo = "";
			}

			return priceInfo;
		},

		// 最少几人起售
		min_user_num: 0,

		// 日历的包裹实体。
		calendar_tip: null,

		// 根据日期数据做出相应的提示，“此套餐需提前预订，如您10月14日出游，请于10月11日21:00前下单”（今天是10月11日，套餐提前3天，21:00前下单。并且14号是最近的可定日期。）
		initCalTip: function(data) {
			// 已经生成过了，就不在生成。
			// if( this.closetDateOfOrderable && this.calendar_tip){
			//   if(this.min_user_num){
			//     fish.one('dd span', this.calendar_tip).html('<span>本套餐' + this.min_user_num + '人起售。</span>')
			//   }else{
			//     fish.one('dd span', this.calendar_tip).html('')
			//   }
			//   return;
			// }

			// 没有有效的时间。
			if (!data.advance && !data.time) {
				// if(this.calendar_tip) {
				//   this.calendar_tip.html('remove');
				//   this.calendar_tip = null;
				// }
				return;
			}

			// 没有最近可定日期，就不显示提示。
			if (!this.closetDateOfOrderable && this.calendar_tip) {
				this.calendar_tip.html('remove');
				this.calendar_tip = null;
				return;
			};

			if (this.calendar_tip) {
				this.calendar_tip.html('remove');
				this.calendar_tip = null;
			}

			if (!this.calendar_tip) {
				fish.all('.overlay_calendar').html('bottom', '<div class="overlay_calendar_tip"></div>');
				this.calendar_tip = fish.all('.overlay_calendar_tip');
			}

			if (data.tip) {
				this.calendar_tip.html('<dl class="clearfix"><dt>友情提示：</dt><dd>' + data.tip + '</dd></dl>');
				return;
			}

			//tip = '友情提示：' + (data.advance ? '此套餐需提前预订，' : '') + '如您' + html_departure + '出游，请于'+ html_order +'前下单。';
			var date_now = {},
				date_departure = {},
				date_order = {},
				t_date_now = fish.parseDate(data.now),
				t_date_departure = fish.parseDate(this.closetDateOfOrderable),
				t_date_order = fish.parseDate(this.closetDateOfOrderable, {
					days: -data.advance
				});

			date_now = {
				year: t_date_now.getFullYear(),
				month: t_date_now.getMonth() + 1,
				day: t_date_now.getDate()
			}

			date_departure = {
				year: t_date_departure.getFullYear(),
				month: t_date_departure.getMonth() + 1,
				day: t_date_departure.getDate()
			};

			date_order = {
				year: t_date_order.getFullYear(),
				month: t_date_order.getMonth() + 1,
				day: t_date_order.getDate()
			};

			var tip = '',
				html_departure = '',
				html_order = '';

			// 出游日期html
			html_departure = date_departure.month + '月' + date_departure.day + '日';
			if (date_departure.year != date_now.year) html_departure = date_departure.year + '年' + html_departure;
			// 下单时间
			html_order = date_order.month + '月' + date_order.day + '日' + data.time;
			if (date_order.year != date_now.year) html_order = date_order.year + '年' + html_order;


			tip = (data.advance ? '本套餐需提前预订，' : '') + '如您' + html_departure + '出游，请于' + html_order + '前下单并支付。<br/>';
			// if(this.min_user_num){
			//   tip += '<span>本套餐' + this.min_user_num + '人起售。</span>'
			// }
			tip = '<dl class="clearfix"><dt>友情提示：</dt><dd>' + tip + '</dd></dl>';
			this.calendar_tip.html(tip);
		},

		// 最接近的可定日期
		closetDateOfOrderable: '',

		resetPices: function(isOrigin) {
			prices = this.prices;

			if (isOrigin) {
				prices = this.router_prices;

				if (prices.length == 2 && prices[0] != prices[1]) {
					prices = prices[0] + '-' + prices[1]
				} else {
					prices = prices[0]
				};

			} else {
				prices = prices[0] + '<span>起</span>'
			}

			fish.all('#router .price .right strong').html(prices);
		}
	}


	/**
	 * packages tab
	 */
	TCent.settings.tab_packages = TCent.settings.tab_packages || {
		url: 'ajax/tab_package.html?'
	}

	TCent.behaviors.tab_packages = {
		attach: function() {
			fish.all('.tab_packages').once('tab-packages', function() {
				// 先初始化dropdown
				var navs = fish.all('.tab_nav li', this);
				if (navs.length >= 2) {
					// 不少于两个
					var first = fish.one(navs[0]),
						last = fish.one(navs[navs.length - 1]),
						max_top = fish.one('.tab_nav li', this).offset().top,
						isOver = false,
						firstOver = false,
						nav_html = '',
						nav_normal = [],
						nav_over = [];

					max_top = fish.one('.tab_nav li', this).offset().top; // 修复chrome下第一次max_top计算为0的bug, 但是为何会出现这样的情况呢？

					if (max_top < last.offset().top || navs.length > 6) {
						// 存在折行的情况。
						for (var i = 0; i < navs.length; i++) {
							if (i <= 6 && !isOver && fish.one(navs[i]).offset().top <= max_top) {
								nav_normal.push(outerHtml(fish.dom(navs[i])));
							} else {
								if (!firstOver) {
									firstOver = true;
									nav_over.push(nav_normal.pop());
								}
								nav_over.push(outerHtml(fish.dom(navs[i])));
							}
						};

						nav_html = nav_normal.join('') + (nav_over.length ? ('<li class="dropdown"><a href="#" class="dropdown_toggle">更多套餐</a><ul class="dropdown_nav">' + nav_over.join('') + '</ul></li>') : '');

						fish.one('.tab_nav', this).html(nav_html);
					}
				}

				TCent.tab_packages.tab = fish.one(this).tab({
					afterClick: function() {
						// 重置secondary nav
						TCent.secondary_nav.reset();

						var pane_html = this.current_pane.html()
						// pane中有内容并且不是加载中的话直接显示就行了
						if (pane_html && fish.trim(pane_html) != '<div class="tab_item_loading"></div>') {
							return;
						}

						// pane中没内容的话加载相应的html
						this.current_pane.html('<div class="tab_item_loading"></div>');

						// 开始获取热门推荐列表
						(function(tab) {
							fish.ajax({
								url: TCent.settings.tab_packages.url + 'routerid=' + TCent.settings.packages.routerid,
								data: 'packageid=' + tab.current_tab.attr('data-package-id'),
								fn: function(data) {
									if (!data) {
										data = '<div class="empty">暂无内容。</div>';
									}

									tab.current_pane.html(data);
									TCent.attachBehaviors();
								}
							})
						})(this);
					}
				});

				function outerHtml(elem) {
					if (typeof elem === "string") elem = document.getElementById(elem);
					// 创建一个空div节点
					var div = document.createElement("div");
					// 将复制的elemCopy插入到空div节点中
					div.appendChild(elem.cloneNode(true));
					// 返回div的HTML内容
					return div.innerHTML;
				};


				fish.all('.package_item', this).once('package-item', function() {
					if (fish.one(this).hasClass('package_snapping')) {
						var Snapping = new TCent.router.Snapping(fish.one(this));
					}

					fish.all('.action a', this).on('click', function(e) {
						fish.preventDefault(e);

						if (fish.one(this).hasClass('pop_toggle')) {
							// 无线弹框，不做任何操作
							return;
						}

						// 点击的按钮是抢购模式
						if (Snapping) {

							if (Snapping.status != 0) {
								// 不是抢购中的，不做任何事
								// do nohting
							} else {
								// 抢购中，直接去下单页
								var url = TCent.settings.packages.url.order + '&routerid=' + TCent.settings.packages.routerid + '&packageid=' + fish.one(this).attr('data-package-id') + '&num=' + 1;
								location.href = url;
							}
							return;
						}

						// 其他正常预订
						var title = '',
							package_item = fish.one(this).getParent('.package_item');

						title = fish.one('h2', package_item).html();

						TCent.packages.id = fish.one(this).attr('data-package-id');
						TCent.packages.min_user_num = fish.one(this).attr('data-user-number');
						package_title = fish.one(this).attr('data-package-title') || '';
						if (TCent.packages.min_user_num) {
							TCent.packages.title = package_title + '<span>(本套餐' + TCent.packages.min_user_num + '人起订，日历框价格为' + TCent.packages.min_user_num + '人价 )</span>';
						} else {
							TCent.packages.title = package_title;
						}
						TCent.packages.submit();
					})
				})

				// fish.all('.action', this).once('package-action', function(){
				//   fish.one(this).on('click', function(e){
				//     fish.preventDefault(e);

				//     var title = '',
				//         package_item = fish.one(this).getParent('.package_item');

				//     title = fish.one('h2',package_item).html();

				//     TCent.packages.id = fish.one(this).attr('data-package-id');
				//     TCent.packages.min_user_num = fish.one(this).attr('data-user-number');
				//     package_title = fish.one(this).attr('data-package-title') || '';
				//     if(TCent.packages.min_user_num){
				//       TCent.packages.title = package_title + '<span>(本套餐' + TCent.packages.min_user_num + '人起订，日历框价格为' + TCent.packages.min_user_num +  '人价 )</span>';
				//     }else{
				//       TCent.packages.title = package_title;
				//     }
				//     TCent.packages.submit();
				//   });
				// })
			})
		}
	}

	TCent.tab_packages = {
		// tab实体。
		tab: null
	}

	/**
	 * hotest_sales
	 */
	TCent.behaviors.hotest_sales = {
		attach: function() {
			fish.all('.hotest_sales').once('hotest-sales', function() {
				// init first one
				var height = fish.one('.current .title_target', this).height();
				fish.one('.current .title_pic').css('height:' + height + 'px');

				// hover
				var that = this;
				fish.all('li', this).on('mouseover', function() {
					if (fish.one(this).hasClass('current')) return;

					var last = fish.all('.current', that), // 上一个hover元素
						current = fish.one(this); // 当前hover元素

					// 重置上一个元素。
					last.removeClass('current');
					fish.one('.title_pic', last).addClass('none');
					fish.one('.tag', last).addClass('none');

					// 重置现在的元素
					current.addClass('current');
					fish.one('.title_pic', current).removeClass('none');
					fish.one('.tag', current).removeClass('none');
					// 为初始化高度的进行初始化
					if (fish.one(".title_pic", current).height() == 0) {
						var dh = fish.one(".title_target", current).height();
						fish.one(".title_pic", current).css("height:" + dh + "px");
					};
				})
			})
		}
	}


	/**
	 * scroll load
	 */
	TCent.behaviors.lazyload = {
		attach: function() {
			// 区块异步加载
			fish.all('body').once('lazyload', function() {
				fish.all('#content .tab_comments_wrapper, #content .subblock_tab_packages .subblock_content', this).scrollLoading({
					callback: function() {
						var css = fish.one('div', this).attr('data-css-link');
						TCent.createCss(css);
						TCent.attachBehaviors();
					}
				})
				fish.all('.ycline_pic img').lazyLoad({
					preSpace: 500
				})
			});
		}
	}

	/**
	 * popover tip
	 */
	TCent.behaviors.popover_tip = {
		attach: function() {
			fish.all('.popover_tip').once('popover-tip', function() {
				var trigger = fish.one(this),
					trigger_value = trigger.attr('data-popover-value'),
					trigger_target = trigger.attr('data-popover-content'),
					trigger_offset = trigger.attr('data-popover-offset'),
					content = '<div class="popover_tip_content ' + trigger_target + '">' + fish.one('.' + trigger_target).html() + '</div>',
					offset = {
						top: 5,
						left: 0
					};

				// 如果在里面设置了值，那么显示的内容是这里的值。
				if (trigger_value) {
					content = '<div class="popover_tip_content ' + trigger_target + '">' + trigger_value + '</div>';
				}

				if (trigger_offset) {
					trigger_offset = trigger_offset.split(',');
					offset.top = parseInt(trigger_offset[0]);
					offset.left = parseInt(trigger_offset[1]);
				}

				var adaptive = false;
				if (fish.one(this).hasClass('price_tooltip')) adaptive = true;

				trigger.popover({
					placement: 'bottom-left',
					trigger: 'hover',
					content: content,
					offset: offset,
					adaptive: adaptive // 关闭自适应，当新的pop不能在当屏显示时，则切换成另一种方式呈现。
				});

				fish.one(this).on('click', function(e) {
					fish.preventDefault(e);
				})
			})
		}
	}

	/**
	 * slider comments
	 */
	TCent.behaviors.slider_comments = {
		attach: function() {
			fish.all('.slider_comments').once('slider-comments', function() {
				that = this;
				fish.require('mSlider', function() {
					if (fish.all('.slider_item', that).length > 1) {
						// 大于1个才需要幻灯。
						TCent.slider_comments.slider = fish.one('.slider_inner', that).mSlider({
							autoScroll: true,
							scrollNum: 1,
							circle: true,
							direction: "y",
							moveTime: 5000,
							showNav: false,
							content: ".slider_item",
							canvas: ".slider_items",
							nextFn: function(obj) {
								// TCent.slider_comments.reset();
								//TCent.slider_comments.collapse();
							},
							beforeNextFn: function() {
								TCent.slider_comments.collapse();
							}
						});
					}


					fish.one(that).addClass('slider_comments_toggleable');

					fish.all('.slider_comments').on('click', function(e) {
						fish.preventDefault(e);
						//TCent.slider_comments.toggle();
						scrollTo(0, fish.one('#comments').offset().top);

						setTimeout(function() {
							fish.all('.secondary_nav li').removeClass('active');
							fish.one(fish.all('.secondary_nav li')[3]).addClass('active')
						}, 300)
					})

					fish.all('.slider_item', that).hover(function() {
						fish.one(this).addClass('hover');
					}, function() {
						fish.one(this).removeClass('hover');
					})
				})

			})
		}
	}

	TCent.slider_comments = {
		slider: null,
		expanded: false,
		current: null,
		expand: function() {
			if (this.expanded || !this.toggleable) return;

			// 开始展开咯
			fish.one('.slider_comments').addClass('slider_comments_expanded');
			this.current.css('height:' + this.height + 'px;');
			fish.one('.slider_comments').css('height:' + this.height + 'px;')
			fish.one('.slider_comments .slider_inner').css('height:' + this.height + 'px;')

			this.expanded = true;
		},
		collapse: function() {
			if (!this.expanded || !this.toggleable) return;

			// 开始收起咯
			fish.one('.slider_comments').removeClass('slider_comments_expanded');
			this.current.css('height:' + this.height_origin + 'px;');
			fish.one('.slider_comments').css('height:' + this.height_origin + 'px;')
			fish.one('.slider_comments .slider_inner').css('height:' + this.height_origin + 'px;')

			this.expanded = false;
		},
		toggle: function() {
			this.expanded ? this.collapse() : this.expand();
		},

		toggleable: false, // 是否可toggle
		height_origin: 0, // 原始高度
		height: 0, // 现内容真实高度
		reset: function() {
			this.current = fish.one('.slider_comments .slider_item');

			// 判断是否需要显示toggle
			this.height_origin = this.height_origin ? this.height_origin : this.current.height();
			this.height = fish.one('.slider_item_inner', this.current).height();

			if (this.height > this.height_origin) {
				// 显示 toggle
				fish.one('.slider_comments').addClass('slider_comments_toggleable');
				this.toggleable = true;
			} else {
				// 不需要显示 toggle
				fish.one('.slider_comments').removeClass('slider_comments_toggleable');
				this.toggleable = false;
			}
		}
	}


	/**
	 * float banner
	 */
	TCent.behaviors.secondary_nav = {
		attach: function() {
			fish.all(".secondary_nav").once('secondary-nav', function() {
				fish.one(this).mFix({
					showType: "float",
					left: 0,
					top: 0,
					content: "#content"
				});

				TCent.secondary_nav.init();

				// 点击按钮弹出地图
				fish.one('.item_traffic', this).on('click', function(e) {
					fish.preventDefault(e);
					TCent.map.overlay.show()
				})
			});

			TCent.secondary_nav.reset();
		}
	}

	TCent.secondary_nav = {
		init: function() {
			if (this.inited) return;
			this.inited = true;
			this.nav = fish.one('.secondary_nav');
			this.nav_items = fish.all('li', this.nav);

			// action按钮的显示高度
			this.action_top = fish.one('.secondary_nav_wrapper').offset().top; //修改定位元素
			this.action = fish.one('li.action', this.nav);

			// 重置mFix
			// if(fish.browser('ms',6)) return; // 性能问题，ie6禁用此功能。
			this.nav.mFix({
				showType: "float",
				left: 0,
				top: 0,
				content: "#content"
			});

			this.reset();
			fish.all(window).on('scroll', fish.proxy(this.check, this));

			// 当点击按钮是，强制高亮该元素。
			this.nav_items.on('click', function(e) {
				TCent.secondary_nav.clicked = true;
				(function(that) {
					TCent.secondary_nav.nav_items.removeClass('active');
					fish.one(that).addClass('active');

					setTimeout(function() {
						TCent.secondary_nav.clicked = false;
					}, 600)
				})(this);
			})

			this.check();

			this.inited = true;
		},
		options: {},
		nav: null, // 导航
		nav_items: null, // 每个导航元素
		tops: [],

		// 重置mfix的触发位置, mFix的触发位置上部发生高度变化时使用。
		resetmFix: function() {
			// @TODO mFix 存在ie6下不能重置触发位置的bug。
			this.nav.mFix({
				showType: "float",
				left: 0,
				top: 0,
				content: "#content"
			});
		},

		reset: function() {
			// 重置 tops 和nav_items
			var tops = [],
				nav_items = [];
			for (var i = 0; i < this.nav_items.length; i++) {
				var nav_item = fish.one(this.nav_items[i]),
					target = this.getTarget(fish.one('a', nav_item).attr('href'));
				if (!nav_item.hasClass('not_nav_item') && target != '#' && fish.one(target).length) {
					nav_items.push(fish.dom(nav_item));
					tops.push(fish.one(target).offset().top);
				}
			}

			this.nav_items = fish.all(nav_items);
			this.tops = tops;
		},
		inited: false,
		// 查看需要哪些高亮。
		check: function() {
			var scrollTop = fish.all(document).scrollTop(),
				top = 0,
				nav_item = null,
				offset_top = 20; // 偏移量

			scrollTop = scrollTop + 20;
			// 是否显示action
			this.checkAction(scrollTop);

			// 如果是点击的，那就不需要重定位。
			if (this.clicked) return;

			for (var i = 0; i < this.tops.length; i++) {
				top = this.tops[i],

					nav_item = i == 0 ? fish.one(this.nav_items[i]) : fish.one(this.nav_items[i - 1])

				if (scrollTop < top) {
					// 当前高亮，其他灰掉。
					this.nav_items.removeClass('active');
					nav_item.addClass('active');
					return;
				}
			}

			// 没有找到就最后一个高亮。
			if (this.nav_items.length) {
				this.nav_items.removeClass('active');
				fish.one(this.nav_items[this.nav_items.length - 1]).addClass('active');
			}
		},

		// 查看是否高亮action按钮
		checkAction: function(scrollTop) {

			console.log(scrollTop);
			console.log(this.action_top);
//			console.log(scrollTop);
			if (scrollTop >= this.action_top) {
				this.action.css('display:block;')
			} else {
				this.action.css('display:none;')
			}
		},

		// get target
		// @return 'www.17u.cn/zizhuyou/#content' 的 '#content'。无匹配则返回 '#content'。
		getTarget: function(target) {
			if (target.indexOf('#') < 0) return '#';

			target = target.substr(target.indexOf('#'), target.length);
			return target;
		}
	}


	/**
	 * bottom_guide
	 */
	TCent.behaviors.bottom_guide = {
		attach: function() {
			fish.all('.bottom_guide').once('bottom-guide', function() {
				TCent.bottom_guide.entry = fish.one(this);
				TCent.bottom_guide.init();
			})
		}
	}

	TCent.bottom_guide = {
		// 初始化
		init: function() {
			this.collapse();

			fish.all('.toggle', this.entry).on('click', fish.proxy(this.toggle, this));
		},

		// 已收起
		collapsed: true,

		// 展开
		expand: function() {
			if (this.animating) return;

			this.animating = true;

			this.entry.addClass('bottom_guide_expanded');
			fish.all('.bottom_guide_inner', this.entry).anim('margin-top:-50px;', 200, function() {
				TCent.bottom_guide.collapsed = false;
				TCent.bottom_guide.animating = false;
				fish.cookie.set('TCent.bottom_guide.collapsed', 0, 7)
			})
		},

		// 收起
		collapse: function() {
			if (this.animating) return;

			this.animating = true;

			this.entry.removeClass('bottom_guide_expanded');
			fish.all('.bottom_guide_inner', this.entry).anim('margin-top:-5px;', 200, function() {
				TCent.bottom_guide.collapsed = true;
				TCent.bottom_guide.animating = false;
				fish.cookie.set('TCent.bottom_guide.collapsed', 1, 7)
			})
		},

		// 展开/收起
		toggle: function() {
			if (this.collapsed) {
				this.expand();
			} else {
				this.collapse();
			}
		},

		// 正在动画中
		animating: false
	}


	/**
	 * pop_tip
	 */
	TCent.behaviors.pop_tip = {
		attach: function() {
			fish.all('.pop_tip').once('popo-tip', function() {
				// 初始化，初始化高度
				TCent.pop_tip.init();

				fish.one(this).on("click", function(e) {
					fish.preventDefault(e);

					TCent.pop_tip.loading();

					// 解决mPop之后遮罩没遮住消失的滚动条问题。
					fish.one('html').css('overflow-y:hidden;');

					// 初始化标题
					fish.one('.overlay_pop_tip .overlay_top_title').html(fish.one(this).html());

					fish.mPop({
						content: fish.one(".overlay_pop_tip"),
						width: 900,
						afterClose : function() {
							// 重新出现滚动条。
							fish.one('html').css('overflow-y:scroll;overflow-x:hidden;');
						}
					})

					fish.ajax({
						url: fish.one(this).attr('href'),
						fn: function(data) {
							if (fish.trim(data) == "") {
								TCent.pop_tip.empty();
							} else {
								fish.one(".overlay_pop_tip .overlay_content").html(data);
							};

							TCent.attachBehaviors();
						}
					})
				})
			})
		}
	}

	TCent.pop_tip = {
		init: function() {
			if (!fish.one('.overlay_pop_tip').length) return;

			fish.one('.overlay_pop_tip').once('tip-content', function() {
				// 初始化tip_content的宽高。
				fish.one('.overlay_content', this).css('height:' + (TCent.pop_tip.getScreenHeight() - 33) + 'px;width:900px;');
			});

			fish.all('.overlay_pop_tip .close').on('click', function(e) {
				fish.preventDefault(e);
				fish.mPop.close();
			})
		},

		loading: function() {
			fish.one(".overlay_pop_tip .overlay_content").html('<div class="loading"></div>');
		},

		empty: function() {
			fish.one(".overlay_pop_tip .overlay_content").html('<div class="empty">暂无内容。</div>');
		},

		getScreenHeight: function() {
			var innerHeight = innerHeight;
			if (innerHeight) return innerHeight;

			return document.documentElement.clientHeight;
		}
	}

	/**
	 * pop_img_list
	 */
	TCent.behaviors.pop_img_list = {
		attach: function() {
			fish.all('.pop_img_list').once('pop-img-list', function() {
				fish.all("li", this).on("mouseover", function() {
					fish.one(this).removeClass("nor")
					fish.one(this).addClass("active")
				})
				fish.all("li", this).on("mouseout", function() {
					fish.one(this).removeClass("active")
					fish.one(this).addClass("nor")
				})


				fish.all("li img", this).hover(function() {
					var nowPosition = fish.one(this).offset(),
						lastoff = fish.one(this).offset().left;
					fish.one("#pop_big_pic").css("position:absolute;");
					var apiShowPosT = nowPosition.top - 6 + "px";
					var apiShowPosL = nowPosition.left + 112 + "px";
					var apiShowPosR = nowPosition.left - 430 + "px";
					if (fish.one(this).hasClass("last")) {
						fish.one("#pop_big_pic").css("left:" + apiShowPosR);
					} else {
						fish.one("#pop_big_pic").css("left:" + apiShowPosL);
					}
					fish.one("#pop_big_pic").css("top :" + apiShowPosT);



					fish.one("#pop_big_pic").css("display:block");
					var url = fish.one(this).attr("bigSrc");
					fish.one("#pop_big_pic img").attr("src", url);

				}, function() {
					fish.one("#pop_big_pic img").attr("src", "");
					fish.one("#pop_big_pic").css("display:none");

				});
			})
		}
	}


	/**
	 * recommend_packages
	 */
	TCent.behaviors.recommend_packages = {
		attach: function() {
			fish.all('#recommend_packages').once('recommend_packages', function() {
				fish.all('li', this).hover(function() {
					fish.one(this).addClass('hover')
				}, function() {
					fish.one(this).removeClass('hover')
				})
			})
		}
	}


	/**
	 * 计算满意度
	 */

	TCent.behaviors.circle_percent = {
		attach:function(){
			fish.all('.circle_percent').once('circle-percent', function(){
				var circle = fish.all(this),
					grade = circle.attr('data-grade') || 0;

				if(grade == 0){
					circle.addClass('circle_percent_0');
					fish.all('.percent', circle).html('暂无<span>满意度</span>');
					return;
				}

				if(!fish.browser("ms")){
					// 非ie采用动画
					DrawCirclePercent(circle, grade);
				}else{
					// ie直接样式
					circle.addClass('circle_percent_num').addClass('circle_percent_' + (grade * 10));
				}
			})


			// 画圆圈
			// @circle dom对象
			// @grade 5分制分数
			function DrawCirclePercent(circle, grade){
				var grade = parseInt(grade/5*100);

				function circlePercent(circle, percent) {
					var circle = circle[0];
					var percent = percent || 0;
					var all = null;
					var left = null;
					var right = null;
					if(circle !== null) {
						all = circle.querySelectorAll("div");
						left =  all[0] || document.createElement("div");
						right = all[1] || document.createElement("div");
						circle.setAttribute("percent", percent);
						if(percent <= 50 && percent >= 0) {
							left.style.visibility = "hidden";
							fish.one(right).css('-webkit-transform: rotate(' + percent * 3.6 + 'deg); -moz-transform: rotate(' + percent * 3.6 + 'deg); -ms-transform: rotate(' + percent * 3.6 + 'deg); -o-transform: rotate(' + percent * 3.6 + 'deg); transform: rotate(' + percent * 3.6 + 'deg);')
						} else if(percent > 50) {
							percent = percent > 100 ? 100 : percent;
							left.style.visibility = "visible";
							fish.one(left).css('-webkit-transform: rotate(' + (percent - 50) * 3.6 + 'deg); -moz-transform: rotate(' + (percent - 50) * 3.6 + 'deg); -ms-transform: rotate(' + (percent - 50) * 3.6 + 'deg); -o-transform: rotate(' + (percent - 50) * 3.6 + 'deg); transform: rotate(' + (percent - 50) * 3.6 + 'deg);')
							fish.one(right).css('-webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg);')
						}
						!all[0] && circle.appendChild(left);
						!all[1] && circle.appendChild(right);
					}
				}

				var t = null;
				var percent = 0;
				if(circle !== null) {
					fish.all('.circle', circle).css('display:block;');
					t = setInterval(function () {
						if(percent >= grade) {
							clearInterval(t);
						} else {
							percent++;
							circlePercent(fish.all('.circle', circle), percent);
							fish.all('.percent span', circle).html(percentToGrade(percent));
						}
					}, 17);
				}

				/**
				 * 百分制转换为五分制
				 */
				function percentToGrade(percent){
					return fish.decimal(percent/100*5, 1).toFixed(1);
				}
			}
		}
	};



	fish.all(".choose_page dd .ch_span7").on("click",function(){
		var _this=fish.one(this);
		var index = fish.all(".choose_page dd .ch_span7").indexOf(this);
		var elem=fish.one(fish.all(".choose_none")[index]);
		if(elem.getCss("display")=="none"){
			if(!elem[0].heightNum){
				elem[0].heightNum=elem.height()-2
			}
			elem.css("display:block;height:0px;");
			elem.anim("height:"+elem[0].heightNum+"px;",500,function(){
				_this.html("收起");
				_this.addClass("ch_span7_nobg");
			});

		}else{
			elem.anim("height:0px;",500,function(){
				elem.css("display:none;");
				_this.html("查看");
				_this.removeClass("ch_span7_nobg");
			});

		}
	});


	// fish.one(fish.all(".tab_content")[1]).addClass("none");
//	tab切换
	fish.all(".journey_place").on("click",function(){
		if(fish.one(this).hasClass("at_journey_place")){return;}

		fish.all(".journey_place").removeClass("at_journey_place");
		fish.one(this).addClass("at_journey_place");
		var index = fish.all(".journey_place").indexOf(this);
		fish.all(".tab_content").addClass("none");
		fish.one(fish.all(".tab_content")[index]).removeClass("none");
	});

	fish.admin.config({
		mSlider: { v: "0.4.3", g: 2013052003, css: 1 }
	});


//	幻灯
	fish.require("mSlider",function(){
		fish.all(".he_slider").each(function(elem,num){
			var allLen = fish.all(".slider_li",elem).length;
			fish.one(".turn_play span",elem).html("1/"+allLen);
			var sliderIndex = 1;
			var msliders = fish.one(elem).mSlider({
				canvas: ".slider_ul",
				content: ".slider_li",
				prevBtn: ".turn_left",
				nextBtn: ".turn_right",
				arrows: true,
				showNav: false,
				circle:true,
//				prevBtnDisabled:"turn_left_hover",
//				nextBtnDisabled:"turn_right_hover",
                nextFn:function(obj){
                	sliderIndex ++;
                	if(sliderIndex > allLen){
                		sliderIndex = 1;
                	}
                    fish.one(".turn_play span",elem).html(sliderIndex + "/" + allLen);
                },
	            prevFn:function(obj){
	            	sliderIndex --;
	            	if(sliderIndex < 1){
	            		sliderIndex = allLen;
	            	}
	                fish.one(".turn_play span",elem).html(sliderIndex + "/" + allLen)
	            }
			});

			fish.one(".turn_play a",elem).on("click",function(){
				if(fish.one(this).hasClass("turn_play_a_start")){
					fish.one(this).removeClass("turn_play_a_start");
					msliders.startScroll();
				}else{
					fish.one(this).addClass("turn_play_a_start");
					msliders.stopScroll();
				}

			});
			if(num >= 2){
				fish.one(fish.all(".tab_content")[1]).addClass("none");
			}

		});
	});


	var moveIndex= 2,InT;
	function moveTop(){
		InT = setInterval(function(){
			if(moveIndex>=fish.all(".comment_info").length+2){return;}

			fish.one(fish.all(".comment_info")[moveIndex]).removeClass("none");
			//fish.dom(".comment_part").scrollTop +=fish.one(fish.all(".comment_info")[moveIndex]).height()+60;
			scrollTo(fish.one(fish.all(".comment_info")[moveIndex]).height()+60,50);
			moveIndex++;

			//console.log(moveIndex);

		},3000);

		//console.log(InT);
	}

	moveTop();


	function scrollTo(distance, time) {
		var nowTop = fish.dom(".comment_part").scrollTop,
			runTimes = 10,
			setTime = time / runTimes;

		for (var i = 0; i < runTimes; i++) {
			setTimeout(function() {
				fish.dom(".comment_part").scrollTop=fish.dom(".comment_part").scrollTop+ parseInt(distance / runTimes);
//				$(window).scrollTop(document.body.scrollTop + parseInt(distance / runTimes));
				//					console.log(document.body.scrollTop);
			}, setTime += time);
			//				console.log(setTime+=time/runTimes);
		}
	}

	fish.one(".comment_part").hover(
		function(){
			clearTimeout(InT);
		},
		function(){
			moveTop();
		}
	)

	fish.all(".choose_page dd .ch_span3 span").hover(
		function(){
			fish.one(".apiShowBox",this).css("display:block;");
		},
		function(){
			fish.one(".apiShowBox",this).css("display:none;");
		}
	);


	fish.all(".upgrade input").on("change",function(){

		if(this.checked == true){
			fish.all(".upgrade input").each(function(){
				this.checked=false;
			});
		}
		this.checked=true;

		var parent = fish.one(this).parent(".checkbox_li");
		var homeStr =fish.one(".font_dashed",parent).html();
		var index = fish.all(".choose_none").indexOf(parent[0]);
		var seleElem = fish.one(fish.all(".sele_elem")[index]);

		fish.one(".home_name",fish.all(".sele_elem")[seleElem]).html(homeStr);
		if(this.checked == false){
			fish.one(".home_name",fish.all(".sele_elem")[seleElem]).html(fish.one(".home_name",fish.all(".sele_elem")[seleElem]).attr("data"));
		}

	});

})();